<template>
  <div>
    <el-card>
      <div slot="header">
        <span>设置促销商品优惠</span>
        <el-button
          type="primary"
          style="float: right"
          @click="prevStep"
        >返回上一步</el-button>
      </div>
      <el-row>
        <el-col :span="12">
          <el-button
            :disabled="this.selectKeys.length == 0"
            @click="batchSet"
          >批量设置</el-button>
          <el-button
            :disabled="this.selectKeys.length == 0"
            @click="batchDrop"
          >批量撤出</el-button>
        </el-col>
        <el-col :span="12">
          <el-form style="float: right" :inline="true" :model="queryParam">
            <el-form-item label="关键字">
              <el-input
                v-model="queryParam.QueryKey"
                placeholder="商品名\SKU"
                @change="search"
              />
            </el-form-item>
            <el-form-item>
              <el-button @click="resetSearch">重置</el-button>
              <el-button type="success" @click="chiose">选择促销商品</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <w-table
        :data="dataList"
        :is-paging="false"
        :columns="columns"
        :is-select="true"
        :is-multiple="true"
        max-height="600px"
        :select-keys="selectKeys"
        row-key="Id"
        @selected="
          (e) => {
            this.selectKeys = e.keys;
          }
        "
      >
        <template slot="activityList" slot-scope="e">
          <template v-if="e.row.Items && e.row.Items.length > 0">
            <p>
              促销价范围：{{ e.row.Items.Min("ActivityPrice") }}-{{
                e.row.Items.Max("ActivityPrice")
              }}
            </p>
            <P v-for="(item, index) in e.row.Items" :key="item.ActivityId">{{
              index +
                1 +
                "，" +
                item.ActivityTitle +
                "，促销价：" +
                item.ActivityPrice +
                "元。"
            }}</P>
          </template>
          <template v-else> 同时段未参与其它单品和套餐类促销 </template>
        </template>
        <template slot="SpecsShow" slot-scope="e">
          <span style="white-space: pre">{{ e.row.SpecsShow }}</span>
        </template>
        <template slot="ActivityPrice" slot-scope="e">
          <el-input-number
            v-model="e.row.ActivityPrice"
            :min="0.1"
            :max="e.row.OriginalPrice"
            style="width: 95%"
            :precision="1"
            @change="save(e.row)"
          />
        </template>
        <template slot="IsMust" slot-scope="e">
          <el-checkbox
            v-model="e.row.IsMust"
            @change="save(e.row)"
          />
        </template>
        <template slot="GoodsName" slot-scope="e">
          <span
            :style="{ color: GoodsStatus[e.row.GoodsStatus].color }"
          >({{ GoodsStatus[e.row.GoodsStatus].text }})</span>
          <span>{{ e.row.GoodsName }}</span>
        </template>
        <template slot="sku" slot-scope="e">
          <div class="sku">
            <div class="img">
              <el-avatar
                shape="square"
                :size="80"
                :src="e.row.SkuImg"
              />
            </div>
            <div class="content">
              <div class="item">
                <span
                  v-if="e.row.SkuIsEnable"
                  style="color: #43af2b"
                >(已启用)</span>
                <span v-else style="color: #e4393c">(已停用)</span>
                {{ e.row.SkuName }}
              </div>
              <div class="skuNo">编号：{{ e.row.GoodsSku }}</div>
            </div>
          </div>
        </template>
        <template slot="action" slot-scope="e">
          <el-button
            size="mini"
            type="danger"
            title="撤出"
            icon="el-icon-delete"
            circle
            @click="drop(e.row)"
          />
        </template>
      </w-table>
      <el-row style="text-align: center; margin-top: 20px">
        <el-button
          :loading="loading"
          type="primary"
          @click="nextStep"
        >下一步</el-button>
        <el-button @click="prevStep">上一步</el-button>
      </el-row>
    </el-card>
    <chioseSku
      :visible="visible"
      :sku-id="skuId"
      :is-multiple="true"
      @save="saveSku"
      @close="visible = false"
    />
    <el-dialog
      title="批量设置"
      :visible="batchVisible"
      width="600px"
      :close-on-click-modal="false"
    >
      <el-form label-width="120px">
        <el-form-item label="折扣比例">
          <el-input-number
            v-model="discountRatio"
            :min="0.1"
            :max="10"
            :precision="1"
            placeholder="折扣比例"
          />
        </el-form-item>
        <el-form-item label="小数位">
          <el-switch
            v-model="precision"
            active-text="保留整数"
            inactive-text="保留一位"
          />
        </el-form-item>
      </el-form>
      <el-row style="text-align: center; margin-top: 20px">
        <el-button
          :loading="loading"
          type="success"
          @click="batchSave"
        >保存</el-button>
        <el-button @click="resetBatch">重置</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>

<script>
import { GoodsStatus } from '@/shop/config/shopConfig'
import * as skuApi from '@/shop/api/activityGoods'
import chioseSku from '@/shop/components/goods/chioseSku.vue'
export default {
  components: {
    chioseSku
  },
  props: {
    isLoad: {
      type: Boolean,
      default: false
    },
    activityType: {
      type: Number,
      default: 0
    },
    id: {
      type: String,
      default: null
    }
  },
  data() {
    return {
      GoodsStatus,
      loading: false,
      batchVisible: false,
      discountRatio: 10,
      skuList: [],
      dataList: [],
      selectKeys: [],
      visible: false,
      precision: true,
      skuId: null,
      activity: {},
      queryParam: {
        QueryKey: null
      },
      columns: [
        {
          key: 'GoodsName',
          title: '商品名',
          align: 'left',
          minWidth: 140,
          slotName: 'GoodsName',
          fixed: 'left'
        },
        {
          key: 'sku',
          title: '规格名',
          align: 'left',
          slotName: 'sku',
          minWidth: 300,
          fixed: 'left'
        },
        {
          key: 'SpecsShow',
          title: '规格说明',
          align: 'left',
          slotName: 'SpecsShow',
          minWidth: 150
        },
        {
          key: 'OriginalPrice',
          title: '原价格',
          align: 'center',
          minWidth: 100
        },
        {
          key: 'ActivityPrice',
          title: '促销价',
          align: 'center',
          slotName: 'ActivityPrice',
          minWidth: 100
        },
        {
          key: 'IsMust',
          title: '是否必须',
          align: 'center',
          slotName: 'IsMust',
          width: 90
        },
        {
          key: 'activityList',
          title: '正在参与的促销活动',
          align: 'left',
          slotName: 'activityList',
          minWidth: 255
        },
        {
          key: 'action',
          title: '操作',
          align: 'center',
          slotName: 'action',
          minWidth: 100
        }
      ]
    }
  },
  computed: {},
  watch: {
    isLoad: {
      handler(val) {
        if (val) {
          this.init()
        }
      },
      immediate: true
    }
  },
  methods: {
    async batchDrop() {
      if (this.selectKeys == null || this.selectKeys.length == 0) {
        return
      }
      await skuApi.BatchDelete(this.id, this.selectKeys)
      this.loadSku()
    },
    nextStep() {
      this.$emit('next')
    },
    prevStep() {
      this.$emit('prev')
    },
    async batchSave() {
      this.batchVisible = false
      const data = []
      this.selectKeys.forEach((c) => {
        const item = this.skuList.find((a) => a.Id == c)
        if (item) {
          item.ActivityPrice = this.precision
            ? Math.round((item.OriginalPrice * this.discountRatio) / 10)
            : Math.round(item.OriginalPrice * this.discountRatio) / 10
          data.push({
            Id: c,
            Price: item.ActivityPrice
          })
        }
      })
      await skuApi.BatchSetPrice(this.id, data)
      this.$message({
        type: 'success',
        message: '保存成功!'
      })
    },
    resetBatch() {
      this.discountRatio = 10
    },
    batchSet() {
      this.discountRatio = 10
      this.precision = true
      this.batchVisible = true
    },
    init() {
      if (this.activityType != 2) {
        const index = this.columns.findIndex((c) => c.key == 'IsMust')
        if (index != -1) {
          this.columns.splice(index, 1)
        }
      }
      this.loadSku()
    },
    async drop(row) {
      await skuApi.Delete(row.Id)
      const index = this.skuList.findIndex((c) => c.Id == row.Id)
      if (index != -1) {
        this.skuList.splice(index, 1)
        this.reset(this.skuList)
      }
    },
    async save(row) {
      await skuApi.SetPrice(row.Id, row.ActivityPrice, row.IsMust)
    },
    chiose() {
      this.visible = true
    },
    reset(list) {
      this.skuId = list.map((c) => c.SkuId)
      this.queryParam.QueryKey = null
      this.dataList = list
      this.selectKeys = []
    },
    async saveSku(e) {
      this.visible = false
      this.skuId = e.keys
      this.skuList = await skuApi.Set(
        this.id,
        e.skus.map((c) => {
          return {
            GoodsId: c.GoodsId,
            SkuId: c.SkuId
          }
        })
      )
      this.reset(this.skuList)
    },
    resetSearch() {
      this.reset(this.skuList)
    },
    search() {
      if (this.queryParam.QueryKey == null || this.queryParam.QueryKey == '') {
        this.reset(this.skuList)
        return
      }
      this.selectKeys = []
      this.dataList = this.skuList.filter(
        (c) =>
          c.SkuName.includes(this.queryParam.QueryKey) ||
          c.GoodsSku.includes(this.queryParam.QueryKey)
      )
    },
    async loadSku() {
      const res = await skuApi.Gets(this.id)
      this.skuList = res
      this.reset(res)
    }
  }
}
</script>

<style  scoped>
.sku {
  width: 100%;
  height: 80px;
}
.sku .img {
  width: 80px;
  float: left;
  height: 80px;
  text-align: center;
}
.sku image {
  width: 100%;
}
.sku .content {
  display: flow-root;
  text-align: left;
}
.sku .content .item {
  margin: 0;
  padding-left: 5px;
  font-size: 16px;
  text-overflow: ellipsis;
  width: 100%;
  overflow: hidden;
  display: inline-block;
  white-space: break-spaces;
  line-height: 20px;
  max-height: 40px;
}

.sku .content .skuNo {
  padding-left: 10px;
  margin: 0;
  color: #82848a;
  font-size: 12px;
  text-overflow: ellipsis;
  width: 100%;
  overflow: hidden;
  display: inline-block;
  white-space: nowrap;
}
.sku .content i {
  font-weight: 600;
}
</style>
